package com.abe.libquick.widget.selector;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.abe.libcore.view.recyclerview.RecyclerViewTool;
import com.abe.libquick.R;
import com.abe.libquick.widget.base.BaseCusRView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

public class AbeSelector<T extends AbeSelectEntity> extends BaseCusRView implements View.OnClickListener
        , OnItemClickListener {
    private final String pleaseChoose = "请选择";
    private View baseView;
    private List<T> entities;//全部数据
    private List<T> tabEntities;//已选中
    private List<T> menuEntities;//当前列表显示选项
    private List<String> tabNames;
    private BaseQuickAdapter<String, BaseViewHolder> tabAdapter;
    private BaseQuickAdapter<T, BaseViewHolder> menuAdapter;
    private OnSelectListener<T> listener;
    private String rootId;
    private boolean isCanChooseHasGroup = false;//是否可以选中含有子项的菜单
    private T currentP;

    public AbeSelector(Context context) {
        super(context);
    }

    public AbeSelector(Context context, List<T> entities, String rootId, OnSelectListener<T> listener) {
        super(context);
        this.rootId = rootId;
        this.entities = entities;
        this.listener = listener;
    }

    @Override
    protected int getRootViewId() {
        return R.id.item_base_v;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_abe_bottom_selector;
    }

    @Override
    protected void initContent() {
        baseView = findViewById(R.id.item_empty_v);
        RecyclerView itemRvTab = findViewById(R.id.item_rv_tab);
        RecyclerView itemRvMenu = findViewById(R.id.item_rv_menu);
        findViewById(R.id.item_empty_v).setOnClickListener(this);
        findViewById(R.id.item_selector_v).setOnClickListener(this);
        tabNames = new ArrayList<>();
        tabNames.add("请选择");
        entities = new ArrayList<>();
        tabEntities = new ArrayList<>();
        menuEntities = new ArrayList<>();
        tabAdapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.area_areatab, tabNames) {
            @Override
            protected void convert(@NonNull BaseViewHolder holder, String item) {
                holder.setText(R.id.item_tabname, item);
                if (holder.getLayoutPosition() == tabNames.size() - 1) {
                    holder.setBackgroundColor(R.id.item_tabimage, getResources().getColor(R.color.colorTheme));
                    holder.setTextColor(R.id.item_tabname, getResources().getColor(R.color.colorTheme));
                } else {
                    holder.setBackgroundColor(R.id.item_tabimage, Color.TRANSPARENT);
                    holder.setTextColor(R.id.item_tabname, Color.BLACK);
                }
            }
        };
        menuAdapter = new BaseQuickAdapter<T, BaseViewHolder>(R.layout.area_areaname, menuEntities) {
            @Override
            protected void convert(@NonNull BaseViewHolder holder, T item) {
                holder.setText(R.id.item_area_name, item.onGetName());
                if (item.onGetStatus()) {
                    holder.setTextColor(R.id.item_area_name, getResources().getColor(R.color.colorTheme));
                    holder.setTextColor(R.id.item_area_select, getResources().getColor(R.color.colorTheme));
                } else {
                    holder.setTextColor(R.id.item_area_name, Color.parseColor("#666666"));
                    holder.setTextColor(R.id.item_area_select, Color.TRANSPARENT);
                }
            }
        };
        tabAdapter.setOnItemClickListener(this);
        menuAdapter.setOnItemClickListener(this);
        itemRvTab.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        itemRvTab.setAdapter(tabAdapter);
        itemRvMenu.addItemDecoration(RecyclerViewTool.colorRes(getContext(), R.color.txt_d));
        itemRvMenu.setLayoutManager(new LinearLayoutManager(getContext()));
        itemRvMenu.setAdapter(menuAdapter);
        initSelector(entities, rootId);
    }

    public void initSelector(List<T> entities, String rootId) {
        currentP = null;
        this.entities = entities;
        this.rootId = rootId;
        tabNames.clear();
        tabEntities.clear();
        menuEntities.clear();
        tabNames.add(pleaseChoose);
        menuEntities.addAll(getBeansByPid(rootId));
        tabAdapter.notifyDataSetChanged();
        menuAdapter.notifyDataSetChanged();
    }

    public void setListener(OnSelectListener<T> listener) {
        this.listener = listener;
    }

    public void setCanChooseHasGroup(boolean canChooseHasGroup) {
        isCanChooseHasGroup = canChooseHasGroup;
    }

    public void setCurrentId(String id) {
        resetSelectStatus();
        T currentBean = getBeanById(id);
        if (currentBean == null) {
            initSelector(entities, rootId);
            return;
        }
        currentP = getBeanById(currentBean.onGetPId());
        //** 更新tab */
        tabNames.clear();
        tabEntities.clear();
        List<String> temTabNames = new ArrayList<>();
        List<T> temTabBeans = new ArrayList<>();
        //** 更新菜单 */
        menuEntities.clear();
        if (isCanChooseHasGroup) {
            //** 选中地区含有子地区 */
            if (getBeansByPid(id).size() > 0) {
                if (currentBean.onCanShowAsSelfChild())
                    menuEntities.add(currentBean);
                menuEntities.addAll(getBeansByPid(id));
                temTabNames.add(currentBean.onGetName());
                temTabBeans.add(currentBean);
            } else {
                menuEntities.add(getBeanById(currentBean.onGetPId()));
                menuEntities.addAll(getBeansByPid(currentBean.onGetPId()));
            }
        } else {
            menuEntities.addAll(getBeansByPid(currentBean.onGetPId()));
        }
        currentBean.setSelect(true);
        String temPid = currentBean.onGetPId();
        while (!temPid.equals(rootId)) {
            T bean = getBeanById(temPid);
            if (bean != null) {
                temTabNames.add(bean.onGetName());
                temTabBeans.add(bean);
                temPid = bean.onGetPId();
            }
        }
        for (int i = temTabNames.size() - 1; i >= 0; i--) {
            tabNames.add(temTabNames.get(i));
            tabEntities.add(temTabBeans.get(i));
        }
        tabNames.add(pleaseChoose);
        tabAdapter.notifyDataSetChanged();
        menuAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter == tabAdapter) {
            //** 点击非最后一项 */
            if (position < tabNames.size() - 1) {
                resetSelectStatus();
                String currentPid = tabEntities.get(position).onGetPId();
                //** 更新tab */
                if (tabEntities.size() > position) {
                    tabEntities.subList(position, tabEntities.size()).clear();
                }
                tabNames.clear();
                for (int i = 0; i < tabEntities.size(); i++) {
                    tabNames.add(tabEntities.get(i).onGetName());
                    if (tabEntities.size() > 0 && i == tabEntities.size() - 1) {
                        currentP = tabEntities.get(i);
                    }
                }
                tabNames.add(pleaseChoose);
                //** 更新菜单 */
                menuEntities.clear();
                if (isCanChooseHasGroup) {
                    T bean = getBeanById(currentPid);
                    if (bean != null && bean.onCanShowAsSelfChild()) {
                        menuEntities.add(bean);
                    }
                }
                menuEntities.addAll(getBeansByPid(currentPid));
                tabAdapter.notifyDataSetChanged();
                menuAdapter.notifyDataSetChanged();
            }
        } else {
            T temBean = menuEntities.get(position);
            if (isCanChooseHasGroup) {
                if (temBean.onCanShowAsSelfChild()) {
                    if (currentP != null && temBean.onGetId().equals(currentP.onGetId())
                            && position == 0 && menuEntities.size() != 1) {
                        updateSelect(position);
                        //** 选择自身，完毕 */
                        listener.OnSelect(temBean);
                        dismiss();
                    } else {
                        List<T> temBeans = getBeansByPid(temBean.onGetId());
                        if (temBeans.size() == 0) {
                            updateSelect(position);
                            //** 无子menu，选择自身，完毕 */
                            listener.OnSelect(temBean);
                            dismiss();
                        } else {
                            currentP = temBean;
                            //** 展开子menu */
                            //** 更新tab */
                            tabEntities.add(temBean);
                            tabNames.clear();
                            for (int i = 0; i < tabEntities.size(); i++) {
                                tabNames.add(tabEntities.get(i).onGetName());
                            }
                            tabNames.add(pleaseChoose);
                            //** 更新menu */
                            menuEntities.clear();
                            menuEntities.add(temBean);
                            menuEntities.addAll(temBeans);
                            tabAdapter.notifyDataSetChanged();
                            menuAdapter.notifyDataSetChanged();
                        }
                    }
                } else {
                    currentP = temBean;
                    List<T> temBeans = getBeansByPid(temBean.onGetId());
                    if (temBeans.size() > 0) {
                        tabEntities.add(temBean);
                        tabNames.clear();
                        for (int i = 0; i < tabEntities.size(); i++) {
                            tabNames.add(tabEntities.get(i).onGetName());
                        }
                        tabNames.add(pleaseChoose);
                        //** 更新menu */
                        menuEntities.clear();
                        menuEntities.addAll(temBeans);
                        tabAdapter.notifyDataSetChanged();
                        menuAdapter.notifyDataSetChanged();
                    }
                }
            } else {
                currentP = temBean;
                List<T> temBeans = getBeansByPid(temBean.onGetId());
                if (temBeans.size() == 0) {
                    updateSelect(position);
                    //** 无子menu，选择自身，完毕 */
                    listener.OnSelect(temBean);
                    dismiss();
                } else {
                    //** 展开子menu */
                    //** 更新tab */
                    tabEntities.add(temBean);
                    tabNames.clear();
                    for (int i = 0; i < tabEntities.size(); i++) {
                        tabNames.add(tabEntities.get(i).onGetName());
                    }
                    tabNames.add(pleaseChoose);
                    //** 更新menu */
                    menuEntities.clear();
                    menuEntities.addAll(temBeans);
                    tabAdapter.notifyDataSetChanged();
                    menuAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.item_empty_v) {
            if (listener != null) listener.OnCancel();
            dismiss();
        } else if (id == R.id.item_selector_v) {
            //doNothing
            System.out.println("item_selector_v");
        }
    }

    private void updateSelect(int choosePos) {
        if (menuEntities == null) return;
        for (int i = 0; i < menuEntities.size(); i++) {
            T temBean = menuEntities.get(i);
            if (i == choosePos) {
                temBean.setSelect(true);
            } else {
                temBean.setSelect(false);
            }
            menuEntities.set(i, temBean);
        }
    }

    /**
     * 重置状态
     */
    private void resetSelectStatus() {
        if (entities == null) return;
        for (int i = 0; i < entities.size(); i++) {
            entities.get(i).setSelect(false);
        }
    }

    private List<T> getBeansByPid(String pid) {
        if (entities == null) return new ArrayList<>();
        List<T> beans = new ArrayList<>();
        for (int i = 0; i < entities.size(); i++) {
            T temBean = entities.get(i);
            if (pid.equals(temBean.onGetPId())) {
                beans.add(temBean);
            }
        }
        return beans;
    }

    private T getBeanById(String id) {
        if (entities == null) return null;
        for (int i = 0; i < entities.size(); i++) {
            T temBean = entities.get(i);
            if (id.equals(temBean.onGetId())) {
                return temBean;
            }
        }
        return null;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        ViewGroup.LayoutParams params = baseView.getLayoutParams();
        params.height = getScreenHeight(context) - getStatusHeight(context) - dip2px(context, 300);
        baseView.setLayoutParams(params);
    }

    public void show() {
        super.show();
        if (menuAdapter != null)
            menuAdapter.notifyDataSetChanged();
        if (tabAdapter != null)
            tabAdapter.notifyDataSetChanged();
    }

    public interface OnSelectListener<T> {
        void OnCancel();

        void OnSelect(T entity);
    }
}